from rest_framework import serializers
from oauth.utils import decode_sign_openid
from users.models import User
from django_redis import get_redis_connection
from .models import OAuthQQUser


class OAuthQQUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label="加密openid")
    mobile = serializers.RegexField(label="手機號",regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(max_length=5,min_length=5,label="短信驗證碼")
    password = serializers.CharField(min_length=8,max_length=20,label="密碼")


    def validate(self, attrs):
        # 校驗openid
        openid = decode_sign_openid(attrs["access_token"])

        if not openid:
            raise serializers.ValidationError("openid錯誤")

        # 校驗短信驗證碼
        mobile = attrs["mobile"]
        sms_code = attrs["sms_code"]

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)

        if not redis_sms_code:
            raise serializers.ValidationError("驗證碼已過期")

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("驗證碼不正確")

        # 校驗密碼
        user = None
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            if not user.check_password(attrs["password"]):
                raise serializers.ValidationError("密碼錯誤")

        attrs["openid"] = openid
        attrs["user"] = user

        return attrs


    def create(self, validated_data):
        # 獲取數據
        openid = validated_data["openid"]
        user = validated_data["user"]

        # 判斷user是否存在
        if not user:
            user = User.objects.create_user(
                username=validated_data["mobile"],
                password=validated_data["password"],
                mobile=validated_data["mobile"]
            )

        # 創建OAuthQQUser對象,綁定美多用戶
        OAuthQQUser.objects.create(openid=openid,user=user)

        return user
